import React, { Component } from 'react';
import RadiosTable from '../radiosTable';
import LayerModel from '../layerModel';
import Ability from '../ability';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Modal, Typography, message } from 'antd';
import { connect } from 'dva';

const { Text } = Typography;

const numIndex = 9;

const mapStateToProps = (state: any) => {
  return {
    // loading: state.loading.effects['ability/getDataWithRes'],
    // permissions: state?.menu?.permissions,
    // rightList: state?.ability?.pageData,
  };
};

class ability extends Component<any> {
  state = {
    layerColumns: [],
    isNext: false,
    list: [],
    searchList: [],
    listLoading: false,
    brandId: '',
    brandOptions:[],
  };
  query = {};
  refAbility = null;
  layerRef = React.createRef();
  tableRef = null;
  nameIndex = ['', '二级', '三级', '四级', '五级', '六级', '七级', '八级', '九级', '十级'];

  refTr = React.createRef();
  fixedObj = {};

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
    // 获取基础命令
    this.getSearchList();
    this.getBrand();
    // this.addDrag();
  }
  //   componentWillUnmount(): void {
  //     document.removeEventListener('drag', this.handleDrag);
  //   }
  //获取品牌数据
  getBrand = () =>{
    const { dispatch } = this.props;
    dispatch({
      type: 'basedata/brandFetch',
      callback: (res:any) => {
        this.setState({ 
           brandOptions: res?.data,
          });
        }
    });
  };
  getSearchList = (commandName: string = '', bool = false) => {
    const { dispatch } = this.props;
    const { layerColumns, searchList } = this.state;
    dispatch({
      type: 'ability/getDataWithRes',
      payload: { url: '/remote/config/base/command/page', commandName, pageSize: 50 },
      callback: res => {
        let obj = {};
        const data = res?.data?.list || [];

        if (bool) {
          layerColumns[2].options = data;
          obj = { layerColumns: [...layerColumns] };
        } else {
          obj = {
            searchList: data,
          };
        }
        this.setState(obj);
      },
    });
  };

  postOnchange = async (record, close) => {
    const { getPrevList, dispatch} = this.props;
    const {
      sid,
      itemCode,
      itemName,
      commandId,
      featureParams,
      tips,
      point,
      imageCondition,
      lastNode,
    } = record;
    const type = sid ? 'edit' : 'save';

    const params = {
      itemCode,
      itemName,
      commandId,
      featureParams,
      tips,
      point,
      imageCondition,
      lastNode: lastNode[0] || 0,
    };
    const query = this.getQuery();
    Object.assign(params, sid ? { sid } : query);

    // 提交
    dispatch({
      type: 'ability/postObjWithRes',
      payload: { url: `/remote/config/base/feature/item/${type}`, ...params },
      callback: res => {
        // 关闭
        close();
        if (res.statusCode === '0') {
          // 刷新数据
          this.getList();
          // 提示
          message.success(`${sid ? '更新' : '新增'}成功`);
          // 刷新上一级数据
          getPrevList && getPrevList();
        }
      },
    });
  };
  initList = query => {
    this.query = { ...this.query, ...query };
    this.getList();
  };
  getQuery = () => {
    const { index = 0 } = this.props;
    const { featureType = '', parentId = '', brandId = '' } = this.query;
    const params = {
      featureType,
      brandId,
      level: index + 1,
    };
    this.setState({
      brandId: brandId,
    })
    parentId && Object.assign(params, { parentId });
    return params;
  };
  // 获取数据
  getList = () => {
    const params = this.getQuery();
    const { dispatch } = this.props;
    this.setState({
      listLoading: true,
    });
    return new Promise(resolve => {
      dispatch({
        type: 'ability/getDataWithRes',
        payload: { url: '/remote/config/base/feature/item/list', ...params },
        callback: res => {
          this.setState({
            list: res.data,
            listLoading: false,
          });
          resolve(res.data);
        },
      });
    });
  };

  postDelete = (record, close) => {
    const { dispatch } = this.props;

    dispatch({
      type: 'ability/postObjWithRes',
      payload: { url: `/remote/config/base/feature/item/delete/${record.sid}` },
      callback: res => {
        // 关闭
        close();

        if (res.statusCode === '0') {
          // 刷新数据
          this.getList();
          // 提示
          message.success('删除成功');

          this.isNextReset();
        }
      },
    });
  };
  // 获取标题名称
  getTitle = (bool = false) => {
    const { index = 0 } = this.props;
    const num = bool ? (index + 1 > numIndex ? 0 : index + 1) : index;

    return `${num > 0 ? this.nameIndex[num] : ''}功能`;
  };
  // 获取表格数据
  getColumns = () => {
    const title = this.getTitle();
    const { index = 0 } = this.props;
    const bool = index > 0;

    let arr = [
      {
        title: title.length < 4 ? `${title}名称` : title,
        dataIndex: 'itemName',
        render: (text, record, index) => {
          const textBool = record.lastNode;
          return <Text type={textBool ? 'warning' : 'default'}>{text}</Text>;
        },
      },
      {
        title: '功能编号',
        dataIndex: 'itemCode',
      },
    ];
    // 判断显示2列还是4列
    if (bool) {
      arr = [
        ...arr,
        {
          title: '基础命令',
          dataIndex: 'commandId',
          render: txt => {
            const { searchList } = this.state;

            const item = searchList.find(e => {
              return e.sid === txt;
            });

            return item?.commandName;
          },
        },
        {
          title: '功能参数',
          dataIndex: 'featureParams',
        },
      ];
    }
    return arr;
  };

  handleSearch = (val: string) => {
    this.getSearchList(val, true);
  };

  // 弹层数据
  getLayerColumns = (title = '', obj = {}) => {
    const { index = 0 } = this.props;
    const bool = index > 0;
    const label = `${title}名称`;
    let layerColumns = [
      {
        type: 'select',
        formItem: {
          name: 'brandId',
          label: '品牌',
          rules: [{ required: false, message: '请选择品牌' }],
        },
        label: {
          disabled: true,
          placeholder: '请选择品牌',
          showSearch: true,
          filterOption: false,
          fieldNames: {
            label: 'brandName',
            value: 'brandCode',
          },
        },
        options: this.state.brandOptions || [],
      },
      {
        type: 'input',
        formItem: {
          name: 'itemName',
          label,
          rules: [{ required: true, message: `请输入${label}` }],
        },
        label: {
          placeholder: `请输入${label}`,
        },
      },
      {
        type: 'input',
        formItem: {
          name: 'itemCode',
          label: '功能编号',
          rules: [{ required: true, message: '请输入功能编号' }],
        },
        label: {
          placeholder: '请输入功能编号',
          maxLength: 50,
        },
      },
    ];
    if (bool) {
      layerColumns = [
        ...layerColumns,
        {
          type: 'select',
          formItem: {
            name: 'commandId',
            label: '基础命令',
          },
          label: {
            placeholder: '请选择基础命令',
            onSearch: this.handleSearch,
            showSearch: true,
            filterOption: false,
            fieldNames: {
              label: 'commandName',
              value: 'sid',
            },
          },
          options: this.state.searchList || [],
        },
        {
          type: 'input',
          formItem: {
            name: 'featureParams',
            label: '功能参数',
          },
          label: {
            placeholder: '请输入功能参数',
          },
        },
        {
          type: 'input',
          formItem: {
            name: 'imageCondition',
            label: (
              <span>
                图片显示条件
                <br />
                （imgcondition）
              </span>
            ),
            className: 'layer-status-delay',
          },
          label: {
            placeholder: '请输入图片显示条件',
            maxLength: 500,
          },
        },
        {
          type: 'inputNumber',
          formItem: {
            name: 'point',
            label: (
              <span>
                数据埋点
                <br />
                （point）
              </span>
            ),
            className: 'layer-status-delay',
          },
          label: {
            placeholder: '请输入埋点数据',
          },
        },
        {
          type: 'input',
          formItem: {
            name: 'tips',
            label: (
              <span>
                提示文言
                <br />
                （tips）
              </span>
            ),
            className: 'layer-status-delay',
          },
          label: {
            placeholder: '请输入提示文言',
          },
        },
        {
          type: 'checkbox',
          formItem: {
            name: 'lastNode',
            wrapperCol: { offset: 6, span: 16 },
          },
          options: [
            {
              value: 1,
              label: '末级功能',
            },
          ],
        },
      ];
    }

    this.setState({
      layerColumns,
    });
    // 打开弹层
    this.layerRef?.current?.setInitVal(`${obj.sid ? '编辑' : '新增'}${title}`, {
      ...obj,
      brandId: this.state.brandId,
      //   commandId: obj.commandId ? obj.commandId : undefined,
      lastNode: [obj.lastNode || 0],
    });
  };
  //   拖拽
  addDrag = () => {
    // 拖拽
    document.addEventListener('drag', this.handleDrag);
    document.addEventListener('dragend', this.handleDragend);
  };
  handleDragStart = (event: any, props: any) => {
    const id = props['data-row-key'];
    event?.dataTransfer?.setData('id', id);
    // const drawImage = this.refTr[id]?.current;
    // if (drawImage) {
    //   event?.dataTransfer?.setDragImage(drawImage, 40, 40);
    // }

    // if (ev.target.nodeType === Node.ELEMENT_NODE) {
    // const previewImage = new Image();
    // previewImage.src =
    //   '';
    // const dragBox = event.target;
    // dragBox.dragData = {};
    // const axis = dragBox.getAttribute('axis');
    // const _axis = axis;
    // event.dataTransfer.setData('text', '');
    // event.dataTransfer.setDragImage(previewImage, 0, 0);
    // const rect = dragBox.getBoundingClientRect();
    // const left = rect.left;
    // const top = rect.top;
    // const startX = event.clientX;
    // const startY = event.clientY;
    // const offsetX = startX - left;
    // const offsetY = startY - top;
    // dragBox.style.transition = 'none';
    // const cloneObj = document.createElement('DIV');
    // const fakeObj = dragBox.cloneNode(true);
    // fakeObj.style.width = dragBox.offsetWidth + 'px';
    // fakeObj.style.height = dragBox.offsetHeight + 'px';
    // fakeObj.style.transform = 'translate3d(0,0,0)';
    // fakeObj.setAttribute('dragging', '');
    // cloneObj.appendChild(fakeObj);
    // cloneObj.className = 'drag-obj';
    // cloneObj.style = 'transform:translate3d( ' + left + 'px ,' + top + 'px,0);';

    // document.body.appendChild(cloneObj);
    // this.fixedObj = {
    //   ...this.fixedObj,
    //   dragBox,
    //   axis,
    //   _axis,
    //   offsetX,
    //   offsetY,
    //   startX,
    //   startY,
    // };
    // }
  };
  handleDrag = event => {
    // console.log(event.clientX, event.clientY);
    if (this.refTr?.current) {
      //   this.refTr.current.style =
      //     'transform:translate3d( ' + event.clientX + 'px ,' + event.clientY + 'px,0);';
      const o = this.refTr.current;
      let posX = 0,
        posY = 0; //临时变量值
      const e = event || window.event; //标准化事件对象
      if (e.pageX || e.pageY) {
        //获取鼠标指针的当前坐标值
        posX = e.pageX;
        posY = e.pageY;
      } else if (e.clientX || e.clientY) {
        posX = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
        posY = event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
      }
      //   o.style.position = 'absolute'; //定义当前对象为绝对定位
      o.style.top = posY + 'px'; //用鼠标指针的y轴坐标和传入偏移值设置对象y轴坐标
      o.style.left = posX + 'px'; //用鼠标指针的x轴坐标和传入偏移值设置对象x轴坐标
    }
  };
  handleDragend = event => {
    console.log(3, event);
  };
  handleDragOver = (event: any) => {
    event.preventDefault();
  };

  handleDrop = (event: any, props: any, list) => {
    const arr = [...list];
    const oldId = event?.dataTransfer?.getData('id');
    const id = props['data-row-key'];
    let num = 1;
    let isNum = true
    const oldItem = arr.find((e, i) => {
      const bool = `${e.sid}` === oldId;
      if (bool) {
        arr.splice(i, 1);
        isNum = false
      }
      if(e.sid === id && isNum){
        num = 0
      }
      return bool;
    });
    const index = arr.findIndex(e => e.sid === id) + num ;
    
    arr.splice(index, 0, oldItem);
    // this.setState({
    //   list: arr,
    // });
    // 提交修改
    this.postSortIndex(arr);
  };

  postSortIndex = arr => {
    const { dispatch } = this.props;
    const list = arr.map((e, i) => {
      const {
        sid,
        itemCode,
        itemName,
        commandId,
        featureParams,
        tips,
        point,
        imageCondition,
        lastNode,
      } = e;

      return {
        sortIndex: i,
        sid,
        itemCode,
        itemName,
        commandId,
        featureParams,
        tips,
        point,
        imageCondition,
        lastNode,
      };
    });
    dispatch({
      type: 'ability/postListList',
      payload: { url: '/remote/config/base/feature/item/edit/batch', list },
      callback: res => {
        if (res.statusCode === '0') {
          // 刷新数据
          this.getList();
        }
      },
    });
  };

  getNextList = record => {
    this.refAbility?.initList({
      featureType: this.query?.featureType,
      brandId:  this.query?.brandId,
      parentId: record.sid,
    });
  };

  getPrevList = () => {
    const tab = this.tableRef;
    const { selectedRowKeys = [] } = tab?.state;
    // 刷新数据
    this.getList().then(res => {
      // 修改table
      tab?.setIndex(selectedRowKeys[0]);
    });
  };

  isNextReset = () => {
    this.tableRef?.setIndex('');
    this.setState({
      isNext: false,
    });
  };

  render() {
    const { index = 0 } = this.props;
    const { layerColumns, isNext, list = [], listLoading } = this.state;
   
    const titleVal = this.getTitle();
    const tableProps = {
      onRef: ref => {
        this.tableRef = ref;
      },
      scroll: { y: 650 },
      menu: [
        {
          name: '编辑',
          auth: 'itemData_edit',
          onClick: (record: any) => {
            // 取值
            // 打开弹层传值
            this.getLayerColumns(titleVal, record);
          },
        },
        {
          name: '删除',
          auth: 'itemData_delete',
          onClick: (record: any) => {
            let confirmLoading = false;
            Modal.confirm({
              title: '删除',
              content: (
                <>
                  <p>确定要删除当前功能吗？</p>
                  <p>删除后，当前功能下的所有{this.getTitle(true)}都将被删除。</p>
                </>
              ),
              wrapClassName: 'layer-model-box',
              icon: <ExclamationCircleOutlined />,
              onOk: close => {
                // 如果为重复点击
                if (confirmLoading) {
                  return false;
                }
                confirmLoading = true;
                // 点击删除请求接口
                this.postDelete(record, close);
              },
            });
          },
        },
      ],
      columns: this.getColumns(),
      loading: listLoading,
      keyName: 'sid',
      list,
      title: {
        name: titleVal,
        auth: 'itemData_add',
        onClick: () => {
          this.getLayerColumns(titleVal);
        },
      },
      onRow: record => {
        this.refAbility?.isNextReset();
        this.setState(
          {
            isNext: !record.lastNode,
          },
          () => {
            this.getNextList(record);
          },
        );
      },
      components: {
        body: {
          row: (props: any) => {
            const { index = 0 } = this.props;
            const editState = index > 1;
            return (
              <>
                <tr
                  {...props}
                  onDragStart={event => this.handleDragStart(event, props)}
                  onDragOver={this.handleDragOver}
                  onDrop={event => this.handleDrop(event, props, list)}
                  draggable={editState}
                ></tr>
              </>
            );
          },
        },
      },
    };

    return (
      <>
        <LayerModel
          ref={this.layerRef}
          onChange={this.postOnchange}
          columns={layerColumns}
        ></LayerModel>
        <div className="ability-item">
          <RadiosTable {...tableProps}></RadiosTable>
        </div>
        {/* <div style={{ position: 'fixed', left: '0', top: '0' }} ref={this.refTr}>
          1111
        </div> */}
        {index < numIndex && isNext && (
          <Ability
            index={index + 1}
            getPrevList={this.getPrevList}
            onRef={val => (this.refAbility = val)}
          ></Ability>
        )}
      </>
    );
  }
}

export default connect(mapStateToProps)(ability);
